package com.ajview.common.controller;

import com.ajview.common.core.constant.Constants;
import com.ajview.common.core.domain.vo.ResultVo;
import com.ajview.common.utils.RedisUtils;
import com.ajview.common.utils.sign.Base64;
import com.ajview.common.utils.uuid.IdUtils;
import com.ajview.core.config.model.AjViewConfigModel;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhangJunJie
 * @Date 2022-07-07
 * <p>
 * 概要：验证码通用接口
 */
@RestController("/captcha")
public class CaptchaController {

    @Resource
    private RedisUtils redisUtils;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;


    @RequestMapping("/captchaCode.json")
    public JSONObject getCaptchaCode() {
        String codemode = AjViewConfigModel.getCaptchaType();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        // 获取该验证码的key对应的value
        String verifyRedisKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 验证码字符 和 验证码结果
        String capStr = null, code = null;
        BufferedImage image = null;
        try {
            if (Constants.CAPTCHA_PRODUCER_MATH.equals(codemode)) {
                // 根据验证码模式生成验证码字符
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);
            } else if (Constants.CAPTCHA_PRODUCER_CHAR.equals(codemode)) {
                // 根据验证码模式生成验证码字符
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
            }
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);
            String encode = Base64.encode(os.toByteArray());
            // 存储验证码对应的key到redis默认过期时间2分钟
            boolean isRedisSuc = redisUtils.set(verifyRedisKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            if (isRedisSuc) {
                JSONObject result = new JSONObject();
                result.put("base64", "data:image/gif;base64," + encode);
                result.put("uuid", uuid);
                return ResultVo.success(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultVo.error();
    }
}
